#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/6/12 17:39
# @Author : linjinting
# @Project : custom_protocol
# @File : callback_handle.py
# @Software: PyCharm


class CallbackHandle(object):
    def __init__(self, distribute):
        self.m_distribute = distribute
        self.m_call_func_map = dict()

    def register(self, e_name, call_func):
        self.m_call_func_map[e_name] = call_func

    def unregister(self, e_name):
        self.m_call_func_map.pop(e_name, None)

    def event_handle(self, **kwargs):
        e_name = kwargs.get('name', '')
        call_func = self.m_call_func_map.get(e_name)
        # print(call_func, e_name)
        if call_func:
            if e_name == 'read':
                call_func(**kwargs)
                return
            call_func()
        else:
            print('the call [%s] function is not found' % e_name)

    def callback(self, **kwargs):
        msg_type = kwargs.get('type')
        # msg = kwargs.get('msg')
        # level = kwargs.get('level')
        data = kwargs.get('data')
        side = kwargs.get('side')
        channel = kwargs.get('channel', '')
        # caller = kwargs.get('caller')

        self.m_distribute.log(**kwargs)
        if data:
            self.m_distribute.parse(data, channel, side)

        if msg_type == 'event':
            self.event_handle(**kwargs)
